package at.jaki.ubb.crawling.demo.core;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import at.jaki.ubb.crawling.api.CrawlingEngine;
import at.jaki.ubb.crawling.demo.dataFinder.KeplerWebfinder;
import at.jaki.ubb.crawling.demo.db.FsDataBase;
import at.jaki.ubb.crawling.demo.model.StarData;
import at.jaki.ubb.crawling.demo.ui.UiManager;
import at.jaki.ubb.crawling.demo.utils.Utils;
import at.jaki.ubb.crawling.model.Target;

public class Listener implements WindowListener, ActionListener {

	private static final Logger LOG = Logger.getLogger(Listener.class);

	private CrawlingEngine ce;

	public Listener(CrawlingEngine ce) {
		this.ce = ce;
	}

	public void actionPerformed(ActionEvent e) {
		if (UiManager.ACTION_GET_STAR.equals(e.getActionCommand())) {
			List<String> idList = Utils.constructList(UiManager.getInstance().getSearchText());
			LOG.info("add targets: " + idList);
			for (String id : idList) {
				Target<String> t = new Target<String>(0.5D, id, KeplerWebfinder.INPUT_TYPE, id);
				ce.addTarget(t);
			}
		}
		if (UiManager.ACTION_SHOW_STAR.equals(e.getActionCommand())) {
			String selectedId = UiManager.getInstance().getSelected();
			try {
				StarData byId = FsDataBase.getInstance().getById(selectedId);
				UiManager.getInstance().showStar(byId);
			} catch (Exception e1) {
				LOG.error("Could not get star data " + e.getClass().getName());
			}
		}
	}

	public void windowClosing(WindowEvent e) {
		ce.stop();
		FsDataBase.getInstance().saveCatalog();
		System.exit(0);

	}

	public void windowOpened(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowClosed(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowIconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowDeiconified(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowActivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

	public void windowDeactivated(WindowEvent e) {
		// TODO Auto-generated method stub

	}

}
